﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories.UserRepositories;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Web.Lib.Security;
using Icoders.MarketTracker.Web.Lib.Validation;

namespace Icoders.MarketTracker.Web.Areas.SmsAdmin.Controllers
{
    [CustomAuthorize(Roles = "ROLE_SMSADMIN")]
    public class GroupController : Controller
    {
        //
        // GET: /SmsAdmin/Group/
        private IUserGroupRepository _userGroupRepository;
        private IUserGroupRoleRepository _userGroupRoleRepository;
        private IUserRepository _userRepository;
        private IAuditTrailRepository _auditTrailRepository;

        public GroupController(IUserGroupRepository userGroupRepository, IUserGroupRoleRepository userGroupRoleRepository, IUserRepository userRepository, IAuditTrailRepository auditTrailRepository)
        {
            _userGroupRepository = userGroupRepository;
            _userGroupRoleRepository = userGroupRoleRepository;
            _userRepository = userRepository;
            _auditTrailRepository = auditTrailRepository;
        }

        public ActionResult Index()
        {
            var ls = _userGroupRepository.GetAll();
            return View(ls);
        }
        public ActionResult Create()
        {

            return View(new UserGroup());
        }
        [HttpPost]
        public ActionResult Create(UserGroup model)
        {
            try
            {

                _userGroupRepository.Save(model);
                Saveaudit("Added User Group", HttpContext.User.Identity.Name, ActionType.Added);
            }
            catch (DomainValidationException dve)
            {
               
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View(model);
            }
            catch (Exception ex)
            {
               
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View(model);
            }
            return RedirectToAction("Index");
        }
        public ActionResult Edit(int id)
        {
          var group=  _userGroupRepository.GetById(id);
          return View(group);
        }
        [HttpPost]
        public ActionResult Edit(UserGroup model)
        {
            try
            {

                _userGroupRepository.Save(model);
                Saveaudit("Edited User group", HttpContext.User.Identity.Name, ActionType.Updated);
            }
            catch (DomainValidationException dve)
            {

                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View(model);
            }
            catch (Exception ex)
            {

                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View(model);
            }
            return RedirectToAction("Index");
        }
        public ActionResult Assign(int groupId)
        {
            var placeholder = _userGroupRoleRepository.GetPlaceHolder(groupId);

            return View(placeholder);
        }
        [HttpPost]
        public ActionResult Assign(int groupId,string[] cb)
        {
            try
            {
                if(cb!=null)
                {
                    _userGroupRoleRepository.GetAll().Where(s => s.GroupId == groupId).ToList().ForEach(f => Reset(f));
                    for(int i=0;i<cb.Length;i++)
                    {
                        string[] roles = cb[i].ToString().Split(',');
                        UserGroupRole ugr = new UserGroupRole();
                        ugr.Id = int.Parse(roles[0]);
                        ugr.RoleId = int.Parse(roles[1]);
                        ugr.GroupId = groupId;
                        ugr.CanAcces = true;
                        _userGroupRoleRepository.Save(ugr);
                        Saveaudit("Assigned User Group", HttpContext.User.Identity.Name, ActionType.Added);
                    }
                    
                }

            }
            catch (Exception ex)
            {

                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return RedirectToAction("Assign", new { groupId = groupId });
            }


            return RedirectToAction("Assign", new { groupId = groupId });
        }

        private void Reset(UserGroupRole userGroupRole)
        {
            userGroupRole.CanAcces = false;
            _userGroupRoleRepository.Save(userGroupRole);
            Saveaudit("Reset User group", HttpContext.User.Identity.Name, ActionType.Updated);
        }
        public void Saveaudit(string description, string username, ActionType actionType)
        {
            //  private IUserRepository _userRepository;
            //private IAuditTrailRepository _auditTrailRepository;
            // Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
            try
            {
                User user = _userRepository.GetByUsername(username);
                AuditTrail auditTrail = new AuditTrail();
                auditTrail.Description = description;
                auditTrail.UserId = user.Id;
                auditTrail.ActionTypeId = Convert.ToInt32(actionType);
                _auditTrailRepository.Save(auditTrail);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
